package com.finance.capacity.capacityMaintain.controller;

import com.finance.base.constant.BaseConstants;
import com.finance.base.exception.BaseException;
import com.finance.capacity.capacityMaintain.request.MaintainListReq;
import com.finance.capacity.casualDetail.capService.ICasualDetailService;
import com.finance.capacity.common.bean.pojo.CapOrganization;
import com.finance.capacity.common.capService.ICapOrganizationService;
import com.finance.capacity.deliveryDetail.bean.pojo.DeliveryDetailErr;
import com.finance.capacity.deliveryDetail.bean.pojo.DeliveryDetailList;
import com.finance.capacity.deliveryDetail.capService.IDeliveryDetailService;
import com.finance.capacity.siteDetail.bean.pojo.SiteDetailList;
import com.finance.capacity.siteDetail.capService.ISiteDetailService;
import com.finance.capacity.siteDetailLog.bean.pojo.SiteDetailLog;
import com.finance.capacity.siteDetailLog.capService.ISiteDetailLogService;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.system.bean.pojo.User;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: ly
 * @Date: Created in 2017-08-28
 */
@Controller
@RequestMapping("/capacity/maintain")
public class CapacityMaintainController extends BaseController {
    @Resource
    private ISiteDetailService siteDetailService;
    @Resource
    private ICapOrganizationService capOrganizationService;
    @Resource
    private IDeliveryDetailService deliveryDetailService;
    @Resource
    private ICasualDetailService casualDetailService;
    @Resource
    private ISiteDetailLogService siteDetailLogService;

    @RequestMapping("/list")
    public Result getMaintainList(MaintainListReq form){
        if(StringUtils.isBlank( form.getSiteId() ) || StringUtils.isBlank(form.getBeginTime()) || StringUtils.isBlank(form.getEndTime()) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        SiteDetailList siteDetailList = new SiteDetailList();
        siteDetailList.setSiteId(form.getSiteId());
        siteDetailList.setStartTime(form.getBeginTime());
        siteDetailList.setEndTime(form.getEndTime());
        List<SiteDetailList> resultBO = siteDetailService.maintainList(siteDetailList);
        return getSuccessResult(resultBO);
    }

    @RequestMapping("/siteInfo")
    public Result getMaintainSiteInfo( String userCode ){
        if(StringUtils.isBlank( userCode ) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }

        CapOrganization siteInfo = capOrganizationService.maintainSiteInfo(userCode);
        return getSuccessResult(siteInfo);
    }

    @RequestMapping("/siteCapacityInfo")
    public Result getSiteCapInfo( MaintainListReq form ){
        if(StringUtils.isBlank( form.getSiteDetailId() ) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }

        SiteDetailList siteDetailList = siteDetailService.getSiteCapInfo(form.getSiteDetailId());
        return getSuccessResult(siteDetailList);
    }

    @RequestMapping("/deliveryList")
    public Result getDeliveryList( MaintainListReq form ){
        if(StringUtils.isBlank( form.getSiteDetailId() ) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        List<DeliveryDetailList> deliveryDetailLists = deliveryDetailService.getDeliveryList(form.getSiteDetailId());
        return getSuccessResult(deliveryDetailLists);
    }

    @RequestMapping("/casualList")
    public Result getCasualList( MaintainListReq form ){
        if(StringUtils.isBlank( form.getSiteDetailId() ) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        List<DeliveryDetailList> deliveryDetailLists = casualDetailService.getCasualList(form.getSiteDetailId());
        return getSuccessResult(deliveryDetailLists);
    }

    @RequestMapping("/siteLogList")
    public Result getSiteLogList( MaintainListReq form ){
        if(StringUtils.isBlank( form.getSiteDetailId() ) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        List<SiteDetailLog> siteDetailLogs = siteDetailLogService.getMaintainSiteLogList(form.getSiteDetailId());
        return getSuccessResult(siteDetailLogs);
    }

    @RequestMapping("/deliveryModify")
    public Result deliveryModify( String deliverys ){
        if(StringUtils.isBlank( deliverys ) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }

        User user = getAuthUser();
        if(user == null){
            return getFailResult(BaseConstants.ERR_UNKONW_USER,BaseConstants.getErrorMessage(BaseConstants.ERR_UNKONW_USER));
        }
        List<DeliveryDetailErr> deliveryDetailErrs = deliveryDetailService.maintainDeliveryModify(deliverys, user);
        return getSuccessResult(deliveryDetailErrs);
    }

    @RequestMapping("/export")
    public Result exportMaintainList(MaintainListReq form, HttpServletResponse response) throws UnsupportedEncodingException {

        if(StringUtils.isBlank( form.getSiteId() ) || StringUtils.isBlank(form.getBeginTime()) || StringUtils.isBlank(form.getEndTime()) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }

        SiteDetailList siteDetailList = new SiteDetailList();
        siteDetailList.setSiteId(form.getSiteId());
        siteDetailList.setStartTime(form.getBeginTime());
        siteDetailList.setEndTime(form.getEndTime());

        List<SiteDetailList> exportMaintainList = siteDetailService.exportMaintainList(siteDetailList);
        if (exportMaintainList.size() > 0) {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "站点运力列表_" + df.format(new Date()); // 文件名
            String lastStr = ".xls";// 文件名后缀
            fileName = fileName + lastStr;

            // 声明一个工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet("站点运力列表信息");
            sheet.createDrawingPatriarch();//
            HSSFRow row = sheet.createRow(0);
            String[] title = new String[]{"序号", "站点", "总单量", "人效单量", "出勤人数", "站点人效", "普通件", "大学件（核算）", "大学件（原始）", "临时工件", "临时工", "批量件", "日期"};
            for (int i = 0; i < title.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }

            for (int i = 0; i < exportMaintainList.size(); i++) {
                SiteDetailList t = (SiteDetailList) exportMaintainList.get(i);
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(i + 1);
                row.createCell(1).setCellValue(t.getSiteName());
                row.createCell(2).setCellValue(t.getOrderTotalNum());
                row.createCell(3).setCellValue(t.getOrderEfficiencyNum());
                row.createCell(4).setCellValue(t.getWorkerNum());
                row.createCell(5).setCellValue(String.valueOf(t.getSiteEfficiency()));
                row.createCell(6).setCellValue(t.getOrderCommonNum());
                row.createCell(7).setCellValue(t.getDxOrderNumAdjust());
                row.createCell(8).setCellValue(t.getDxOrderNumOriginal());
                row.createCell(9).setCellValue(t.getTempOrderNum());
                row.createCell(10).setCellValue(t.getTempDeliveryNum());
                row.createCell(11).setCellValue(t.getBatchOrderNum());
                row.createCell(12).setCellValue(t.getSiteDate());
            }

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream out;
            try {
                out = response.getOutputStream();
                workbook.write(out);
                out.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return getFailResult(BaseConstants.ERR_INVALID_PARAMETER, BaseConstants.getErrorMessage(BaseConstants.ERR_INVALID_PARAMETER) );
            }
            return null;
        } else {
            return getFailResult(BaseConstants.ERR_RESULT_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_RESULT_NULL) );
        }
    }

}
